#!/usr/bin/env python
# coding=UTF-8
import random
import logging
import json
import time
import datetime

import config
import dao
#import views

from nsq.http import nsqd
import redisco
from redisco.containers import List, Hash

# redisco.connection_setup(host=config.REDIS_HOST, port=config.REDIS_PORT, db=config.REDIS_DB)

def get_match_base_score(bid, mid, all_round, game_round, rid):
    db = dao.Game_DB()
    #match = db.match_info(bid, mid)
    #mround = match['mround']
    #all_round = int(all_round)
    #game_round = int(game_round)
    #win_score = mround * match['score'] + all_round - game_round
    room_info = db.get_room(rid, bid)
    win_score = room_info['base_score'] + all_round - game_round + 1
    return win_score

def json_encode(data):
    return json.dumps(data, separators=(',', ':'))

def nsq_pub(message, topic='response'):
    try:
        nsq_client = nsqd.Client("http://47.93.90.95:4151/")
        if isinstance(message, dict):
            message = json_encode(message)
        logging.info(u"推送消息:%s" % message)
        nsq_client.pub(topic, message)
        return True
    except:
        logging.error("nsq send error", exc_info=True)
        return False
    
def push_room_cast(rid, bid, uid, data):
    rid = data['rid']
    l = List(rid)
    for member in l.members:
        nsq_pub.pub({"d":data, "u":str(member), "b":bid, "t":"game"})
    return 

def push_member_cast(members, bid, uid, data):
    for member in members:
        if not member or member == str(uid):
            continue
        nsq_pub.pub({"d":data, "u":str(member), "b":bid, "t":"game"})
    return

class Player():
    def __init__(self, uid, bid='', first=False):
        self.uid = uid
        if first:
            redisco.connection.delete("p:%s:%s:current_card" % (bid, uid))
            redisco.connection.delete("p:%s:%s:out_card" % (bid, uid))
            redisco.connection.delete("p:%s:%s:dark_bar" % (bid, uid))
            redisco.connection.delete("p:%s:%s:white_bar" % (bid, uid))
            redisco.connection.delete("p:%s:%s:pair" % (bid, uid))
            redisco.connection.delete("p:%s:%s" % (bid, uid))
            self.score = Hash("p:%s:%s" % (bid, uid))
            self.score['score'] = 0
        else:
            self.score = Hash("p:%s:%s" % (bid, uid))
        self.current_card = List("p:%s:%s:current_card" % (bid, uid))
        self.out_card = List("p:%s:%s:out_card" % (bid, uid))
        self.dark_bar = List("p:%s:%s:dark_bar" % (bid, uid))
        self.white_bar = List("p:%s:%s:white_bar" % (bid, uid))
        self.pair = List("p:%s:%s:pair" % (bid, uid))

    def get_data(self):
        return {"uid":self.uid,
                "current_card":self.current_card.members,
                "out_card":self.out_card.members,
                "dark_bar":self.dark_bar.members,
                "white_bar":self.white_bar.members,
                "pair":self.pair.members,
                "score":self.score['score'],
                }

class MaJiang():
    def __init__(self, rid, bid, dealer=None):
        self.rid = str(rid)
        if dealer:
            redisco.connection.delete("r:%s:current_card" % rid)
            # redisco.connection.delete("r:%s" % rid)
            redisco.connection.delete("r:%s:mid" % rid)
            self.room = Hash("r:%s" % rid)
            self.room['dealer'] = dealer
            self.room['last_get_user'] = dealer
            self.room['last_put_user'] = ''
            #game_round = int(self.room.get('game_round', 0))
            #self.room['game_round'] = game_round + 1
            self.room['stop_pop_user'] = ''
            self.room['stop_pop_act'] = ''
        else:
            self.room = Hash("r:%s" % rid)
        self.current_card = List("r:%s:current_card" % rid)
        self.bid = bid
        l = List("r:%s:p" % rid)
        self.members = l.members
    
    def incr_mid(self):
        return redisco.connection.incr("r:%s:mid" % self.rid)
    
    def start(self):
        self.room['status'] = 'start'
        w = [str(x) for x in range(11, 20)] * 4
        d = [str(x) for x in range(21, 30)] * 4
        t = [str(x) for x in range(31, 40)] * 4
        f = [str(x) for x in range(41, 48)] * 4
        random.shuffle(w)
        random.shuffle(d)
        random.shuffle(t)
        random.shuffle(f)
        player_cnt = len(self.members)
        init_left_card = 136 - player_cnt * 13 - 1
        #f = [str(x) for x in range(41, 48)]
        #f = f + sorted(f * 3)
        
        if self.room['game_type'] == 'zzmj':
            #不带风的情况
            all_card = w + d + t
            init_left_card -= 28
        else:
            all_card = w + d + t + f
            
        random.shuffle(all_card)
        
        dealer_seat = self.members.index(self.room['dealer'])
        for i in range(player_cnt):
            idex = (dealer_seat + i) % player_cnt
            uid = self.members[idex]
            player = Player(uid, self.bid, True)
            card = []
            for i in range(13):
                card.append(all_card.pop())
                card.sort()
            player.current_card.extend(card)
            mid = self.incr_mid()
            nsq_pub({"b":self.bid, "u":str(uid), "t":"game", "d":{"left_card":init_left_card, "rid":self.rid, "mid":mid, "act":"game_start", "dealer":self.room['dealer'], "card":card, "game_round":self.room['game_round'], "all_round":self.room['all_round']}})
        dealer = self.room['dealer']
        self.room['last_get_user'] = dealer
        self.current_card.clear()
        self.current_card.extend(all_card)
        logging.info(u"房间rid:%s,game_round:%s,开始发牌: %s" % (self.rid, self.room['game_round'], str(self.current_card.members)))
        self.next_pop(dealer)
    
    def get_horse(self, num, winner):
        seat_horse_card = [['11', '15', '19', '21', '25', '29', '31', '35', '39', '41', '45'],
                           ['12', '16', '22', '26', '32', '36', '42', '46'],
                           ['13', '17', '23', '27', '33', '37', '43', '47'],
                           ['14', '18', '24', '28', '34', '38', '44'],
                           ]
        
        horse_card = []
        dealer = self.room['dealer']
        dealer_seat = self.members.index(str(dealer))
        # 庄家座位
        winner_seat = self.members.index(str(winner))
        # 赢家的座位
        winner_seat_horse = seat_horse_card[winner_seat - dealer_seat]
        # 该赢家对应座位的马牌列表
        current_card = self.current_card.members
        
        all_horse_card = current_card[:num]
        for card in all_horse_card:
            if card in winner_seat_horse:
                horse_card.append(card)
        logging.info(u"获取马牌:num:%s,所有马牌:%s, 已中马牌:%s,种马数量 :%s" % (num, all_horse_card, horse_card, len(horse_card)))
        return all_horse_card, horse_card
        
    def next_pop(self, uid=None, from_bar=False):
        # 发牌逻辑
        if not uid:
            last_get_user = self.room['last_get_user']
            logging.info("next_pop, last:%s" % last_get_user)
            last_player_seat = self.members.index(str(last_get_user))
            idx = (last_player_seat + 1) % len(self.members)
            uid = self.members[idx]
        
        if len(self.current_card.members) <= int(self.room['horse']):
            logging.info("over===cccccccccc========%s" % len(self.current_card.members))
            self.game_over()
            return
        card = self.current_card.pop()
        if not card:
            logging.info("over===========")
            self.game_over()
            return
        if from_bar:
            self.room['bar_get_card'] = card
        else: 
            self.room['bar_get_card'] = ''
            
        p = Player(uid, self.bid)
        # 判断胡牌,杠牌
        tips = []
        bar_card = []
        current_user = Hash("%s_%s" % (self.bid, uid))
        if self.room['mid'] and current_user['online'] != 'y':
            tips = []
            #离线用户不检查牌型
        else:
            if self.check_win(p, card):
                tips.append("win")
            
            current_card = p.current_card.members
            init_dark_bar = self.check_init_dark_bar(current_card)
            if self.check_bar(current_card, card):
                tips.append("dark_bar")
                bar_card.append(card)
            elif self.check_pair_bar(p.pair.members, card):
                tips.append("pair_bar")
                
            if init_dark_bar:
                tips.append("dark_bar")
                bar_card.extend(init_dark_bar)
            
        if tips:
            self.room['stop_pop_user'] = uid
            self.room['stop_pop_act'] = ",".join(tips)
        p.current_card.append(card)
        mid = self.incr_mid()
        left_card = len(self.current_card)
        for member in self.members:
            #if member != uid:
            #    tips = []
            data = {"b":self.bid, "u":str(member), "t":"game", "d":{"left_card":left_card, "mid":mid, "uid":uid, "act":"get_card", "card":card, "tips":tips, "bar_card":bar_card, "rid":self.rid}}
            nsq_pub(data)
        self.room['last_get_user'] = uid
        
        if self.room['mid'] and current_user['online'] != 'y':
            self.room['stop_pop_user'] = ""
            time.sleep(0.5)
            self.put_card(uid, {"card":card})
        
    def put_card(self, uid, data):
        # 玩家出牌逻辑
        stop_pop_user = self.room['stop_pop_user']
        if stop_pop_user and stop_pop_user != str(uid):
            logging.info(u"玩家:%s有提示未处理,轮不到%s出牌" % (stop_pop_user, uid))
            return
        last_get_user = self.room['last_get_user']
        if last_get_user != str(uid):
            logging.info(u"该玩家:%s出牌,轮不到%s出牌" % (last_get_user, uid))
            return
        card = data['card']
        p = Player(uid, self.bid)
        if p.current_card.count(card) == 0:
            logging.info(u"出牌错误,该玩家没有该牌")
            return
        p.out_card.append(card)
        p.current_card.remove(card)
        #print uid, p.current_card.members
        self.room['last_put_user'] = uid
        # 检查别人是否胡牌下发提示
        stop_pop_card = False
        mid = self.incr_mid()
        tips = []
        #game_type = self.room['game_type']
        for member in self.members:
            if member != uid:
                player = Player(member, self.bid)
                current_card = player.current_card.members
                tips = [] 
                #比赛用户离线不做提示
                if self.room['mid']:
                    member_info = Hash("%s_%s" % (self.bid, member))
                    if member_info['online'] != 'y':
                        tips = []
                    else:
                        if self.check_bar(current_card, card):
                            tips.append("bar")
                            tips.append("pair")
                        elif self.check_pair(current_card, card):
                            tips.append("pair")
                else:
                    if self.check_bar(current_card, card):
                        tips.append("bar")
                        tips.append("pair")
                    elif self.check_pair(current_card, card):
                        tips.append("pair")
                
                if tips:
                    stop_pop_card = True
                    self.room['stop_pop_user'] = member
                    self.room['stop_pop_act'] = ",".join(tips)
            else:
                tips = []
            nsq_pub({"b":self.bid, "u":str(member), "t":"game", "d":{"mid":mid, "act":"put_card", "card":card, "tips":tips, "rid":self.rid, "uid":uid}})
            
        if not stop_pop_card:
            self.room['stop_pop_user'] = ""
            self.next_pop()

    def pass_card(self, uid, data):
        logging.info("pass:%s" % uid)
        stop_pop_user = self.room['stop_pop_user']
        if not stop_pop_user:
            logging.info(u"目前没有提示, 不该%s操作" % uid)
            return
        elif stop_pop_user != uid:
            logging.info(u"玩家%s有提示, 不该%s操作" % (stop_pop_user, uid))
            return
        self.room['stop_pop_user'] = ""
        self.room['stop_pop_act'] = ""
        
        if self.room['last_get_user'] != uid:
            self.next_pop()
    
    def get_jiang(self, card):
        r = []
        for k in set(card):
            if card.count(k) >= 2:
                r.append(k)
        return r

    def get_n(self, card, jiang):
        n = 0
        # print "===当将牌为%s时,各种排列组合为==" % jiang
        # logging.info(u"当奖牌为%s时候的组合=======" % jiang)
        res = []
        card.sort()
        card.remove(jiang)
        card.remove(jiang)
        while card:
            c = card.pop(0)
            if card.count(c) == 2:
                n += 1
                card.remove(c)
                card.remove(c)
                res.append([c, c, c])
            elif c > 40:
                break
            else:
                c2 = c + 1
                c3 = c + 2
                if c2 in card and c3 in card:
                    card.remove(c2)
                    card.remove(c3)
                    res.append([c, c2, c3])
                    n += 1
                else:
                    break
        # logging.info(res)
        return n

    def get_max_n(self, card_str):
        allcard = [int(x) for x in card_str]
        ccc = [int(x) for x in card_str]
        jiang_list = self.get_jiang(allcard)
        if not jiang_list:
            return 0
        res = [0, ]
        for jiang in jiang_list:
            ddd = sorted(ccc)
            n = self.get_n(ddd, jiang)
            res.append(n)
        return max(res) + 1

    def check_seven_pairs(self, all_card):
        '''七对胡'''
        jiang_list = self.get_jiang(all_card)
        if not jiang_list:
            return False
        return len(jiang_list) == 7

    def check_thirteen_orphans(self, all_card):
        '''十三幺'''
        jiang_list = self.get_jiang(all_card)
        if len(jiang_list) != 1:
            return False
        jiang = jiang_list[0]
        card_list = ['11', '19', '21', '29', '31', '39', '41', '42', '43', '44', '45', '46', '47']
        if set(all_card) == set(card_list) and jiang in card_list:
            return True
        return False
    
    def check_win(self, player, card=''):
        # 检查
        n = 0
        n += len(player.dark_bar)
        n += len(player.white_bar)
        n += len(player.pair)
        current_card = player.current_card.members
        if card:
            current_card.append(card)
        if n == 0 and self.room['seven_pair_win'] == 'y':
            if self.check_seven_pairs(current_card):
                return True
            #elif self.check_thirteen_orphans(current_card):
            #    return True
        if len(current_card) != ((4 - n) * 3 + 2):
            logging.info(u"该玩家手牌相公不能胡牌:%s" % player.uid)
            return False
        max_n = self.get_max_n(current_card)
        logging.debug(u"用户牌型最大n:%s" % max_n)
        if n + max_n == 5:
            return True
        return False

    def check_init_dark_bar(self, current_card):
        # 检查初始手牌能否暗杠
        res = []
        for k in set(current_card):
            if current_card.count(k) == 4:
                res.append(k)
        return res
    
    def check_dark_bar(self, current_card, card=''):
        # 检查摸的牌能否暗杠
        if current_card.count(card) == 4:
            return True
        return False

    def check_bar(self, current_card, card=''):
        # 检查能否杠
        if current_card.count(card) == 3:
            return True
        return False

    def check_pair_bar(self, pair, card=''):
        # 检查碰过的牌是否摸到杠
        if pair.count(card) >= 1:
            return True
        return False
    
    def check_pair(self, current_card, card=''):
        # 检查能否碰牌
        if current_card.count(card) >= 2:
            return True
        return False
    
    def dark_bar(self, uid, data):
        stop_pop_user = self.room['stop_pop_user']
        if not stop_pop_user:
            logging.info(u"目前没有提示, 不该%s操作" % uid)
            return
        elif stop_pop_user != uid:
            logging.info(u"玩家%s有提示, 不该%s操作" % (stop_pop_user, uid))
            return
        card = data.get('card','')
        p = Player(uid, self.bid)
        current_card = p.current_card.members
        if not card:
            for k in set(current_card):
                if current_card.count(k) == 4:
                    card = k
                    
        if not self.check_dark_bar(current_card, card):
            logging.info(u"请求错误,该用户不能杠牌:%s" % card)
            return
        p.current_card.remove(card, 4)
        p.dark_bar.append(card)
        self.room['stop_pop_user'] = ""
        self.room['stop_pop_act'] = ""
        member_len = len(self.members)
        match_id = self.room['mid']
        if match_id:
            bar_score = 0
            every_lose_score = 0
        else:
            bar_score = (member_len - 1) * 2
            every_lose_score = 2
        mid = self.incr_mid()
        for member in self.members:
            if not match_id:
                if member == uid:
                    p.score['score'] = int(p.score['score']) + bar_score
                    logging.info(u"用户%s暗杠得%s分" % (uid, bar_score))
                else:
                    player = Player(member, self.bid)
                    player.score['score'] = int(player.score['score']) - every_lose_score
                    logging.info(u"用户%s暗杠,%s扣%s分:%s" % (uid, member, every_lose_score, player.score['score']))
            nsq_pub({"b":self.bid, "u":str(member), "t":"game", "d":{"mid":mid, "act":"dark_bar", "card":card, "tips":[], "rid":self.rid, "uid":uid}})
        self.next_pop(uid)

    def pair_bar(self, uid, data):
        # 碰过别的牌, 然后自己摸到一张
        # card = data['card']
        stop_pop_user = self.room['stop_pop_user']
        if stop_pop_user and stop_pop_user != uid:
            logging.info(u"玩家%s有提示, 不该%s操作" % (stop_pop_user, uid))
            return
        p = Player(uid, self.bid)
        card = p.current_card.members[-1]
        if not self.check_pair_bar(p.pair.members, card):
            logging.info(u"请求错误,该用户不能杠牌:%s" % card)
            return
        self.room['stop_pop_user'] = ""
        self.room['stop_pop_act'] = ""
        p.current_card.remove(card)
        p.pair.remove(card)
        p.white_bar.append(card)
        stop_pop_card = False
        
        match_id = self.room['mid']
        if not match_id:
            member_len = len(self.members)
            bar_score = (member_len - 1)
            p.score['score'] = int(p.score['score']) + bar_score
            logging.info(u"用户%s明杠得%s分" % (uid, bar_score))
        mid = self.incr_mid()
        tips = []
        user_seat = self.members.index(uid)
        player_cnt = len(self.members)
        for i in range(player_cnt):
            idex = (user_seat + i) % player_cnt
            member = self.members[idex]
            if member != uid:
                
                player = Player(member, self.bid)
                # 玩家有杠个扣1分
                if not match_id:
                    player.score['score'] = int(player.score['score']) - 1
                    logging.info(u"用户%s明杠,玩家%s各扣1分:%s" % (uid, member, player.score['score']))
                if tips:
                    pass
                else:
                    tips = []
                    if self.room['grab_bar_win'] == 'y':
                        if self.check_win(player, card):
                            tips = ["pair_bar_win"]
                            stop_pop_card = True
                            self.room['stop_pop_user'] = member
                            self.room['stop_pop_act'] = ",".join(tips)
            else:
                tips = []
            nsq_pub({"b":self.bid, "u":str(member), "t":"game", "d":{"mid":mid, "act":"pair_bar", "card":card, "tips":tips, "rid":self.rid, "uid":uid}})
        
        if not stop_pop_card:
            # 有抢杠胡的玩家,需要停止发牌  
            self.next_pop(uid)
        
    def bar(self, uid, data):
        # 自己有三张,直接杠别人出的牌
        # card = data['card']
        # bar_uid = data['put_card_uid']
        stop_pop_user = self.room['stop_pop_user']
        if not stop_pop_user:
            logging.info(u"目前没有提示, 不该%s操作" % uid)
            return
        elif stop_pop_user != uid:
            logging.info(u"玩家%s有提示, 不该%s操作" % (stop_pop_user, uid))
            return
        last_put_user = self.room['last_put_user']
        last_put_player = Player(last_put_user, self.bid)
        
        card = last_put_player.out_card.members[-1]
        p = Player(uid, self.bid)
        current_card = p.current_card.members
        if not self.check_bar(current_card, card):
            logging.info(u"请求错误,该用户不能杠牌:%s" % card)
            return
        card = last_put_player.out_card.pop()
        p.current_card.remove(card, 3)
        p.white_bar.append(card)
        
        match_id = self.room['mid'] 
        if not match_id:
            member_len = len(self.members)
            bar_score = member_len - 1
            p.score['score'] = int(p.score['score']) + bar_score
            logging.info(u"用户%s杠得3分:%s" % (uid, p.score['score']))
        mid = self.incr_mid()
        for member in self.members:
            if member == last_put_user:
                if not match_id:
                    player = Player(member, self.bid)
                    player.score['score'] = int(player.score['score']) - bar_score
                    logging.info(u"用户%s点杠,扣3分:%s" % (member, player.score['score']))
            nsq_pub({"b":self.bid, "u":str(member), "t":"game", "d":{"mid":mid, "act":"bar", "card":card, "tips":[], "rid":self.rid, "uid":uid, "put_card_uid":last_put_user}})
        
        self.room['stop_pop_user'] = ""
        self.room['stop_pop_act'] = ""
        self.next_pop(uid, from_bar=True)
    
    def pair(self, uid, data):
        stop_pop_user = self.room['stop_pop_user']
        if not stop_pop_user:
            logging.info(u"目前没有提示, 不该%s操作" % uid)
            return
        elif stop_pop_user != uid:
            logging.info(u"玩家%s有提示, 不该%s操作" % (stop_pop_user, uid))
            return
        # card = data['card']
        # put_card_uid = data['put_card_uid']
        last_put_user = self.room['last_put_user']
        last_put_player = Player(last_put_user, self.bid)
        card = last_put_player.out_card.members[-1]
        
        p = Player(uid, self.bid)
        current_card = p.current_card.members
        if not self.check_pair(current_card, card):
            logging.info(u"请求错误,该用户不能碰牌:%s" % card)
            return
        card = last_put_player.out_card.pop()
        
        p.current_card.remove(card, 2)
        p.pair.append(card)
        mid = self.incr_mid()
        for member in self.members:
            nsq_pub({"b":self.bid, "u":str(member), "t":"game", "d":{"mid":mid, "act":"pair", "card":card, "tips":[], "rid":self.rid, "uid":uid, "put_card_uid":last_put_user}})
        # p = Player(self.room['lasy_player'], self.bid)
        # p.out_card.remove(card, -1)
        self.room['last_get_user'] = uid
        self.room['stop_pop_user'] = ""
        self.room['stop_pop_act'] = ""

    def win(self, uid, data):
        if self.room['status'] != 'start':
            logging.info(u"该轮游戏已结束")
            return
        stop_pop_user = self.room['stop_pop_user']
        if not stop_pop_user:
            logging.info(u"目前没有提示, 不该%s操作" % uid)
            return
        elif stop_pop_user != uid:
            logging.info(u"玩家%s有提示, 不该%s操作" % (stop_pop_user, uid))
            return
        # card = data.get('card', '')
        
        p = Player(uid, self.bid)
        card = p.current_card.members[-1]
        # if not self.check_win(p, card):
        if not self.check_win(p, ''):
            logging.info(u"请求错误,该用户不能胡牌:%s" % card)
            return
        self.room['stop_pop_user'] = ""
        self.room['stop_pop_act'] = ""
        all_horse_card = []
        horse_card = []
        horse_num = 0
        horse = self.room['horse']
        if horse:
            horse = int(horse)
            all_horse_card, horse_card = self.get_horse(horse, uid)
            horse_num = len(horse_card)
            
        member_len = len(self.members)
        match_id = self.room['mid']
        if match_id:
            #比赛杠没有分
            all_round = int(self.room['all_round'])
            game_round = int(self.room['game_round'])
            base_score = get_match_base_score(self.bid, match_id, all_round, game_round, self.rid)
        else:
            base_score = 1
        every_lose_score = 2 * base_score * (1 + horse_num)
        win_score = every_lose_score * (member_len - 1)
        
        if self.room['bar_get_card'] == card and self.room['bar_win_duty'] == 'y':
            # 杠上开花,杠爆全包
            last_put_user = self.room['last_put_user']
            p.score['score'] = int(p.score['score']) + win_score
            last_put_player = Player(last_put_user, self.bid)
            last_put_player.score['score'] = int(last_put_player.score['score']) - win_score
            logging.info(u"用户%s杠上开花得%s分,点杠者%s全包" % (uid, win_score, last_put_user))
        else:
            p.score['score'] = int(p.score['score']) + win_score
            logging.info(u"用户%s自摸胡牌,中%s马,得%s分" % (uid, horse_num, win_score))
            for member in self.members:
                if member != uid:
                    player = Player(member, self.bid)
                    player.score['score'] = int(player.score['score']) - every_lose_score
                    logging.info(u"用户%s自摸胡牌,中%s马,玩家各扣%s分" % (uid, horse_num, every_lose_score))
        mid = self.incr_mid()
        for member in self.members:
            nsq_pub({"b":self.bid, "u":str(member), "t":"game", "d":{"mid":mid, "act":"win", "card":card, "tips":[], "rid":self.rid, "uid":uid, "all_horse_card":all_horse_card, "horse_card":horse_card, "horse_num":horse_num}})
        self.game_over(uid, card, all_horse_card, horse_card, horse_num, win_type="win")

    def pair_bar_win(self, uid, data):
        # 抢杠胡,杠家全包,退还之前杠的分数
        stop_pop_user = self.room['stop_pop_user']
        if not stop_pop_user:
            logging.info(u"目前没有提示, 不该%s操作" % uid)
            return
        elif stop_pop_user != uid:
            logging.info(u"玩家%s有提示, 不该%s操作" % (stop_pop_user, uid))
            return
        #card = data['card']
        bar_uid = self.room['last_get_user']
        bar_player = Player(bar_uid, self.bid)
        white_bar_member = bar_player.white_bar.members
        if white_bar_member:
            card = white_bar_member[-1]
        else:
            card = data.get("card", "")
        
        p = Player(uid, self.bid)
        if not self.check_win(p, card):
            logging.info(u"请求错误,该用户不能胡牌:%s" % card)
            return
        
        self.room['stop_pop_user'] = ""
        self.room['stop_pop_act'] = ""
        all_horse_card = []
        horse_card = []
        horse_num = 0
        horse = self.room['horse']
        if horse:
            horse = int(horse)
            all_horse_card, horse_card = self.get_horse(horse, uid)
            horse_num = len(horse_card)
        
        member_len = len(self.members)
        match_id = self.room['mid']
        if match_id:
            #比赛杠没有分
            bar_score = 0
            deduct_bar_score = 0
            all_round = int(self.room['all_round'])
            game_round = int(self.room['game_round'])
            base_score = get_match_base_score(self.bid, match_id, all_round, game_round, self.rid)
        else:
            bar_score = 1
            deduct_bar_score = member_len - 1
            base_score = 1
        every_lose_score = 2 * base_score * (1 + horse_num)
        win_score = every_lose_score * (member_len - 1)
        logging.info(u"用户%s抢杠胡,中%s马,得%s分" % (uid, horse_num, win_score))
        
        p.score['score'] = int(p.score['score']) + win_score + bar_score
        mid = self.incr_mid()
        for member in self.members:
            if member != uid:
                player = Player(member, self.bid)
                # 抢杠胡全包
                if member == bar_uid:
                    player.pair.append(card)
                    player.white_bar.remove(card)
                    player.score['score'] = int(player.score['score']) - deduct_bar_score - win_score
                    logging.info(u"用户%s抢杠胡,中%s马,抢杠全包:%s, 扣%s分" % (uid, horse_num, bar_uid, win_score))
                else:
                    player.score['score'] = int(player.score['score']) + bar_score
                    logging.info(u"用户%s抢杠胡,中%s马,抢杠全包,玩家退还杠扣的1分:%s" % (uid, horse_num, member))
            
            nsq_pub({"b":self.bid, "u":str(member), "t":"game", "d":{"mid":mid, "act":"win", "card":card, "tips":[], "rid":self.rid, "uid":uid, "all_horse_card":all_horse_card, "horse_card":horse_card, "horse_num":horse_num}})
        self.game_over(uid, card, all_horse_card, horse_card, horse_num, win_type="pair_bar_win")
        
    def game_over(self, winner='', card='', all_horse_card=[], horse_card=[], horse_num=0, from_dissmiss=False, win_type=""):
        if from_dissmiss:
            from_dissmiss = "y"
        else:
            from_dissmiss = "n"
        dealer = self.room['dealer']
        db = dao.Game_DB()
        player_card = []
        for uid in self.members:
            if not uid:
                continue
            p = Player(uid, self.bid)
            p_data = p.get_data()
            del p_data['out_card']
            if dealer == uid:
                is_dealer = "y"
            else:
                is_dealer = "n"
            p_data['is_dealer'] = is_dealer
            player_card.append(p_data)
            
            # 重置玩家状态,和计算分数
            if not winner:
                score = 0
                p.score['score'] = 0
                p_data['score'] = "0"
            else:
                score = int(p_data['score'])
            db.update_player(self.rid, uid, score, 0)
            player_info = db.get_player(self.rid, uid)
            p_data['user_score'] = player_info['score']
        
        
        rules = {}
        #room_info = db.get_room(self.rid, self.bid)
        #gid = room_info.get("gid")
        gid = self.room['gid']
        if gid:
            rows = db.game_rule(gid)
        else:
            rows = db.room_rule(self.rid)
            gid = ""
        for row in rows:
            k = row['param']
            v = row['value']
            rules[k] = v
        
        #比赛的牌局统一规则
        match_id = self.room['mid']
        if match_id:
            rules = {"horse":0, "grab_bar_win":"y", "grab_bar_duty":"y", "bar_win_duty":"n", "seven_pair_win":"y"}
        else:
            match_id = ""
        game_type = self.room['game_type']
        mid = self.incr_mid()
        room_left_card = self.current_card.members
        for uid in self.members:
            nsq_pub({"b":self.bid, "u":str(uid), "t":"game", "d":{"room_left_card":room_left_card, "match_id":match_id, "gid":gid, "rules":rules, "win_type":win_type,"from_dissmiss":from_dissmiss,"dealer":self.room['dealer'], "game_round":self.room['game_round'], "player_card":player_card, "mid":mid, "act":"game_over", "winner":winner, "card":card, "rid":self.rid, "all_horse_card":all_horse_card, "horse_card":horse_card, "horse_num":horse_num}})
            try:
                if winner == uid:
                    win_round = 1
                else:
                    win_round = 0
                if db.has_user_stat(self.bid, uid, game_type):
                    db.update_user_stat(self.bid, uid, game_type, win_round)
                else:
                    db.add_user_stat(self.bid, uid, game_type, win_round, 0)
            except:
                logging.error(u"统计用户生涯错误:%s" % uid, exc_info=True)
        logging.info("game over")
        if winner:
            self.room['dealer'] = winner
        
        self.room['status'] = 'over'
        self.room['stop_pop_user'] = ''
        self.room['last_put_user'] = ''
        self.room['last_get_user'] = ''
        game_round = int(self.room['game_round'])
        all_round = int(self.room['all_round'])
        db.game_over(self.rid, game_round)
        
        if match_id:
            nsq_pub({"b":self.bid, "u":"", "t":"game", "d":{"all_round":all_round, "match_id":match_id, "rules":rules, "win_type":win_type,"from_dissmiss":from_dissmiss,"dealer":self.room['dealer'], "game_round":self.room['game_round'], "player_card":player_card, "mid":mid, "act":"game_over", "winner":winner, "card":card, "rid":self.rid, "all_horse_card":all_horse_card, "horse_card":horse_card, "horse_num":horse_num}}, "match_club")
        self.room['game_round'] = game_round + 1
        if all_round <= game_round:
            self.dismiss(act='room_over')
        else:
            if match_id:
                exp_time = (datetime.datetime.now() + datetime.timedelta(seconds=15)).strftime("%Y-%m-%d %H:%M:%S")
                db.add_cron(self.bid, "auto_ready", self.rid, 0, exp_time)
        
    def dismiss(self, act='room_over'):
        time.sleep(0.5)
        db = dao.Game_DB()
        player_data = {}
        player_stat = []
        if not self.room['status']:
            logging.info(u"房间结束,未开始:%s" % self.rid)
            deduct_flag = False
            winner = ""
            for uid in self.members:
                player_stat.append({"uid":uid,"horse":0,"dark_bar":0,"white_bar":0,"score":0,"win_num":0})
        else:
            p_stat = db.player_stat(self.rid)
            logging.info(p_stat)
            for ps in p_stat:
                ps['horse'] = int(ps['horse'])
                ps['dark_bar'] = int(ps['dark_bar'])
                ps['white_bar'] = int(ps['white_bar'])
                ps['score'] = int(ps['score'])
                ps['win_num'] = int(ps['win_num'])
                player_data[str(ps['uid'])] = ps
            deduct_flag = True
            if p_stat:
                winner = p_stat[-1]['uid']
            else:
                winner = ""
            # 排序最后一家为大赢家
            player_stat = p_stat
        logging.info("ppppppppppdddddddddddddddddddd")
        logging.info(player_data)
        
        #for uid in self.members:
        #    player_stat.append(player_data.get(str(uid), {}))
            
        room_info = db.get_room(self.rid, self.bid)
        admin = room_info['admin']
        match_id = self.room['mid']
        if not match_id:
            #比赛的房间不发送room_over
            for uid in self.members:
                nsq_pub({"b":self.bid, "u":str(uid), "t":"game", "d":{"act":"room_over", "rid":self.rid, "player_stat":player_stat, "winner":winner, "admin":admin}})
        else:
            #比赛房间不扣房卡
            deduct_flag = False
        db.dismiss_room(self.rid)
        game_type = self.room['game_type']
        gid = self.room['gid']
        if match_id or gid:
            nsq_pub({"b":self.bid, "u":"", "t":"game", "d":{"game_type":game_type, "match_id":match_id, "gid":gid, "act":"room_over", "rid":self.rid, "player_stat":player_stat, "winner":winner, "admin":admin}}, "match_club")
            
        if deduct_flag:
            card = room_info['card']
            db.deduct_card(self.bid, admin, card)
            nsq_pub({"act":"deduct_card", "bid":self.bid, "uid":admin, "card":card, "rid":self.rid}, "total")
            logging.info(u"房间%s解散成功,扣除房卡, bid:%s,uid:%s,card:%s" % (self.rid, self.bid, admin, card))
        else:
            logging.info(u"房间%s解散成功,游戏无需扣房卡" % self.rid)
        redisco.connection.delete("r:%s:current_card" % self.rid)
        redisco.connection.delete("r:%s:out_card" % self.rid)
        redisco.connection.delete("r:%s" % self.rid)
        redisco.connection.delete("r:%s:mid" % self.rid)
        redisco.connection.delete("r:%s:p" % self.rid)


class ZZMaJiang(MaJiang):
    def start(self):
        self.room['status'] = 'start'
        w = [str(x) for x in range(11, 20)] * 4
        d = [str(x) for x in range(21, 30)] * 4
        t = [str(x) for x in range(31, 40)] * 4
        f = [str(x) for x in range(41, 48)] * 4
        random.shuffle(w)
        random.shuffle(d)
        random.shuffle(t)
        random.shuffle(f)
        player_cnt = len(self.members)
        init_left_card = 136 - player_cnt * 13 - 1
        all_card = w + d + t
        init_left_card -= 28
        random.shuffle(all_card)
        
        dealer_seat = self.members.index(self.room['dealer'])
        for i in range(player_cnt):
            idex = (dealer_seat + i) % player_cnt
            uid = self.members[idex]
            player = Player(uid, self.bid, True)
            card = []
            for i in range(13):
                card.append(all_card.pop())
                card.sort()
            player.current_card.extend(card)
            mid = self.incr_mid()
            nsq_pub({"b":self.bid, "u":str(uid), "t":"game", "d":{"left_card":init_left_card, "rid":self.rid, "mid":mid, "act":"game_start", "dealer":self.room['dealer'], "card":card, "game_round":self.room['game_round'], "all_round":self.room['all_round']}})
        dealer = self.room['dealer']
        self.room['last_get_user'] = dealer
        self.current_card.clear()
        self.current_card.extend(all_card)
        logging.info(u"转转麻将房间rid:%s,game_round:%s,开始发牌: %s" % (self.rid, self.room['game_round'], str(self.current_card.members)))
        self.next_pop(dealer)
        
    def put_card(self, uid, data, from_pass=False, repeat_user=[]):
        # 玩家出牌逻辑
        repeat = "n"
        #是否重复发牌给客户端
        if not from_pass:
            stop_pop_user = self.room['stop_pop_user']
            if stop_pop_user and stop_pop_user != str(uid):
                logging.info(u"玩家:%s有提示未处理,轮不到%s出牌" % (stop_pop_user, uid))
                #views.get_last_data('', self.bid, uid, data)
                return
            last_get_user = self.room['last_get_user']
            if last_get_user != str(uid):
                logging.info(u"该玩家:%s出牌,轮不到%s出牌" % (last_get_user, uid))
                #views.get_last_data('', self.bid, uid, data)
                return
            card = data['card']
            p = Player(uid, self.bid)
            if p.current_card.count(card) == 0:
                logging.info(u"出牌错误,该玩家没有该牌")
                return
            p.out_card.append(card)
            p.current_card.remove(card)
            self.room['last_put_user'] = uid
            
            put_win_user = []
            #按照玩家座位顺序检查是否有胡牌可能
            user_seat = self.members.index(uid)
            player_cnt = len(self.members)
            
            for i in range(player_cnt):
                idex = (user_seat + i) % player_cnt
                member = self.members[idex]
                if member != uid:
                    member_info = Hash("%s_%s" % (self.bid, member))
                    if self.room['mid'] and member_info['online'] != 'y':
                        tips = []
                    else:
                        member_player = Player(member, self.bid)
                        tips = [] 
                        if self.check_win(member_player, card):
                            put_win_user.append(member)
                                
            if len(put_win_user) >= 1:
                #点炮胡的情况
                self.room['stop_pop_user'] = ",".join(put_win_user)
                self.room['stop_pop_act'] = "put_win"
                tips = ["put_win"]
                #self.room['stop_pop_act'] = "pair_bar_win,put_win"
                #tips = ["pair_bar_win"]
                mid = self.incr_mid()
                nsq_pub({"b":self.bid, "u":str(put_win_user[0]), "t":"game", "d":{"mid":mid, "act":"put_card", "card":card, "tips":tips, "rid":self.rid, "uid":uid}})
                return
        
        card = data['card']
        self.room['last_put_user'] = uid
        stop_pop_card = False
        tips = []
        game_type = self.room['game_type']
        
        mid = self.incr_mid()
        for member in self.members:
            if member != uid:
                member_info = Hash("%s_%s" % (self.bid, member))
                if self.room['mid'] and member_info['online'] != 'y':
                    tips = []
                else:
                    player = Player(member, self.bid)
                    current_card = player.current_card.members
                    tips = [] 
                    if self.check_bar(current_card, card):
                        tips.append("bar")
                        tips.append("pair")
                    elif self.check_pair(current_card, card):
                        tips.append("pair")
                if tips:
                    stop_pop_card = True
                    self.room['stop_pop_user'] = member
                    self.room['stop_pop_act'] = ",".join(tips)
            else:
                tips = []
            if member in repeat_user:
                repeat = "y"
            else:
                repeat = "n"
            nsq_pub({"b":self.bid, "u":str(member), "t":"game", "d":{"repeat":repeat, "mid":mid, "act":"put_card", "card":card, "tips":tips, "rid":self.rid, "uid":uid}})
            
        if not stop_pop_card:
            self.next_pop()

    def pass_card(self, uid, data):
        logging.info("pass:%s" % uid)
        stop_pop_user = self.room['stop_pop_user']
        if not stop_pop_user:
            logging.info(u"目前没有提示, 不该%s操作" % uid)
            return
        elif uid not in stop_pop_user.split(","):
            logging.info(u"玩家%s有提示, 不该%s操作" % (stop_pop_user, uid))
            return
        if "put_win" in self.room['stop_pop_act']:
            last_put_user = self.room['last_put_user']
            p = Player(last_put_user, self.bid)
            card = p.out_card.members[-1]
            stop_pop_user_list = stop_pop_user.split(",")
            idx = stop_pop_user_list.index(uid)
            if len(stop_pop_user_list) != (idx+1):
                #给下一家可胡牌玩家推送通知
                next_player = stop_pop_user_list[idx+1]
                mid = self.incr_mid()
                tips = ["put_win"]
                #tips = ["pair_bar_win"]
                nsq_pub({"b":self.bid, "u":str(next_player), "t":"game", "d":{"mid":mid, "act":"put_card", "card":card, "tips":tips, "rid":self.rid, "uid":uid}})
            else:
                self.room['stop_pop_user'] = ""
                self.room['stop_pop_act'] = ""
                data = {"card":card}
                self.put_card(last_put_user, data, True, stop_pop_user_list)
            return
                
        self.room['stop_pop_user'] = ""
        self.room['stop_pop_act'] = ""
        
        if self.room['last_get_user'] != uid:
            self.next_pop()

    def pair_bar(self, uid, data):
        # 碰过别的牌, 然后自己摸到一张
        # card = data['card']
        stop_pop_user = self.room['stop_pop_user']
        if stop_pop_user and stop_pop_user != uid:
            logging.info(u"玩家%s有提示, 不该%s操作" % (stop_pop_user, uid))
            return
        p = Player(uid, self.bid)
        card = p.current_card.members[-1]
        if not self.check_pair_bar(p.pair.members, card):
            logging.info(u"请求错误,该用户不能杠牌:%s" % card)
            return
        self.room['stop_pop_user'] = ""
        self.room['stop_pop_act'] = ""
        p.current_card.remove(card)
        p.pair.remove(card)
        p.white_bar.append(card)
        stop_pop_card = False
        match_id = self.room['mid'] 
        if not match_id:
            member_len = len(self.members)
            bar_score = (member_len - 1)
            p.score['score'] = int(p.score['score']) + bar_score
            logging.info(u"用户%s明杠得%s分" % (uid, bar_score))
        mid = self.incr_mid()
        tips = []
        
        user_seat = self.members.index(uid)
        player_cnt = len(self.members)
        for i in range(player_cnt):
            idex = (user_seat + i) % player_cnt
            member = self.members[idex]
            if member != uid:
                player = Player(member, self.bid)
                if not match_id:
                    # 玩家有杠个扣1分
                    player.score['score'] = int(player.score['score']) - 1
                    logging.info(u"用户%s明杠,玩家%s各扣1分:%s" % (uid, member, player.score['score']))
                if tips:
                    pass
                else:
                    tips = []
                    if self.room['grab_bar_win'] == 'y':
                        if self.check_win(player, card):
                            tips = ["pair_bar_win"]
                            stop_pop_card = True
                            self.room['stop_pop_user'] = member
                            self.room['stop_pop_act'] = ",".join(tips)
            else:
                tips = []
            nsq_pub({"b":self.bid, "u":str(member), "t":"game", "d":{"mid":mid, "act":"pair_bar", "card":card, "tips":tips, "rid":self.rid, "uid":uid}})
        
        if not stop_pop_card:
            # 有抢杠胡的玩家,需要停止发牌  
            self.next_pop(uid)
        
    def bar(self, uid, data):
        # 自己有三张,直接杠别人出的牌
        # card = data['card']
        # bar_uid = data['put_card_uid']
        stop_pop_user = self.room['stop_pop_user']
        if not stop_pop_user:
            logging.info(u"目前没有提示, 不该%s操作" % uid)
            return
        elif stop_pop_user != uid:
            logging.info(u"玩家%s有提示, 不该%s操作" % (stop_pop_user, uid))
            return
        last_put_user = self.room['last_put_user']
        last_put_player = Player(last_put_user, self.bid)
        
        card = last_put_player.out_card.members[-1]
        p = Player(uid, self.bid)
        current_card = p.current_card.members
        if not self.check_bar(current_card, card):
            logging.info(u"请求错误,该用户不能杠牌:%s" % card)
            return
        card = last_put_player.out_card.pop()
        p.current_card.remove(card, 3)
        p.white_bar.append(card)
        
        match_id = self.room['mid']
        if not match_id:
            #只有非比赛房间才对杠扣分
            member_len = len(self.members)
            bar_score = member_len - 1
            p.score['score'] = int(p.score['score']) + bar_score
            logging.info(u"用户%s杠得3分:%s" % (uid, p.score['score']))
        mid = self.incr_mid()
        for member in self.members:
            if member == last_put_user:
                if not match_id:
                    player = Player(member, self.bid)
                    player.score['score'] = int(player.score['score']) - bar_score
                    logging.info(u"用户%s点杠,扣3分:%s" % (member, player.score['score']))
            nsq_pub({"b":self.bid, "u":str(member), "t":"game", "d":{"mid":mid, "act":"bar", "card":card, "tips":[], "rid":self.rid, "uid":uid, "put_card_uid":last_put_user}})
        
        self.room['stop_pop_user'] = ""
        self.room['stop_pop_act'] = ""
        self.next_pop(uid, from_bar=True)
    
    def pair(self, uid, data):
        stop_pop_user = self.room['stop_pop_user']
        if not stop_pop_user:
            logging.info(u"目前没有提示, 不该%s操作" % uid)
            return
        elif stop_pop_user != uid:
            logging.info(u"玩家%s有提示, 不该%s操作" % (stop_pop_user, uid))
            return
        # card = data['card']
        # put_card_uid = data['put_card_uid']
        last_put_user = self.room['last_put_user']
        last_put_player = Player(last_put_user, self.bid)
        card = last_put_player.out_card.members[-1]
        
        p = Player(uid, self.bid)
        current_card = p.current_card.members
        if not self.check_pair(current_card, card):
            logging.info(u"请求错误,该用户不能碰牌:%s" % card)
            return
        card = last_put_player.out_card.pop()
        
        p.current_card.remove(card, 2)
        p.pair.append(card)
        mid = self.incr_mid()
        for member in self.members:
            nsq_pub({"b":self.bid, "u":str(member), "t":"game", "d":{"mid":mid, "act":"pair", "card":card, "tips":[], "rid":self.rid, "uid":uid, "put_card_uid":last_put_user}})
        # p = Player(self.room['lasy_player'], self.bid)
        # p.out_card.remove(card, -1)
        self.room['last_get_user'] = uid
        self.room['stop_pop_user'] = ""
        self.room['stop_pop_act'] = ""


    def pair_bar_win(self, uid, data):
        
        if "put_win" in self.room['stop_pop_act']:
            self.put_win(uid, data)
            return
        
        # 抢杠胡,杠家全包,退还之前杠的分数
        stop_pop_user = self.room['stop_pop_user']
        if not stop_pop_user:
            logging.info(u"目前没有提示, 不该%s操作" % uid)
            return
        elif stop_pop_user != uid:
            logging.info(u"玩家%s有提示, 不该%s操作" % (stop_pop_user, uid))
            return
        #card = data['card']
        bar_uid = self.room['last_get_user']
        bar_player = Player(bar_uid, self.bid)
        white_bar_member = bar_player.white_bar.members
        if white_bar_member:
            card = white_bar_member[-1]
        else:
            card = data.get("card", "")
        
        p = Player(uid, self.bid)
        if not self.check_win(p, card):
            logging.info(u"请求错误,该用户不能胡牌:%s" % card)
            return
        
        self.room['stop_pop_user'] = ""
        self.room['stop_pop_act'] = ""
        all_horse_card = []
        horse_card = []
        horse_num = 0
        horse = self.room['horse']
        if horse:
            horse = int(horse)
            all_horse_card, horse_card = self.get_horse(horse, uid)
            horse_num = len(horse_card)
        
        member_len = len(self.members)
        match_id = self.room['mid']
        if match_id:
            #比赛杠没有分
            bar_score = 0
            deduct_bar_score = 0
            all_round = int(self.room['all_round'])
            game_round = int(self.room['game_round'])
            base_score = get_match_base_score(self.bid, match_id, all_round, game_round, self.rid)
        else:
            bar_score = 1
            deduct_bar_score = member_len - 1
            base_score = 1
        every_lose_score = 2 * base_score * (1 + horse_num)
        win_score = every_lose_score * (member_len - 1)
        logging.info(u"用户%s抢杠胡,中%s马,得%s分" % (uid, horse_num, win_score))
        p.score['score'] = int(p.score['score']) + win_score + bar_score
        mid = self.incr_mid()
        for member in self.members:
            if member != uid:
                player = Player(member, self.bid)
                # 抢杠胡全包
                if member == bar_uid:
                    player.pair.append(card)
                    player.white_bar.remove(card)
                    player.score['score'] = int(player.score['score']) - deduct_bar_score - win_score
                    logging.info(u"用户%s抢杠胡,中%s马,抢杠全包:%s, 扣%s分" % (uid, horse_num, bar_uid, win_score))
                else:
                    if bar_score != 0:
                        player.score['score'] = int(player.score['score']) + bar_score
                        logging.info(u"用户%s抢杠胡,中%s马,抢杠全包,玩家退还杠扣的1分:%s" % (uid, horse_num, member))
            
            nsq_pub({"b":self.bid, "u":str(member), "t":"game", "d":{"mid":mid, "act":"win", "card":card, "tips":[], "rid":self.rid, "uid":uid, "all_horse_card":all_horse_card, "horse_card":horse_card, "horse_num":horse_num}})
        self.game_over(uid, card, all_horse_card, horse_card, horse_num, win_type="pair_bar_win")

    def put_win(self, uid, data):
        #点炮胡
        stop_pop_user = self.room['stop_pop_user']
        if not stop_pop_user:
            logging.info(u"目前没有提示, 不该%s操作" % uid)
            return
        elif uid not in stop_pop_user.split(","):
            logging.info(u"玩家%s有提示, 不该%s操作" % (stop_pop_user, uid))
            return
        last_put_user = self.room['last_put_user']
        last_put_player = Player(last_put_user, self.bid)
        card = last_put_player.out_card.members[-1]
        logging.info("last_put_user:%s, card:%s" % (last_put_user, card))
        p = Player(uid, self.bid)
        if not self.check_win(p, card):
            logging.info(u"请求错误,该用户不能胡牌:%s" % card)
            return
        
        data['card'] = card
        for member in self.members:
            if member == uid:
                continue
            mid = self.incr_mid()
            nsq_pub({"b":self.bid, "u":str(member), "t":"game", "d":{"mid":mid, "act":"put_card", "card":card, "tips":[], "rid":self.rid, "uid":last_put_user}})
        #self.put_card(uid, data, True)
        
        self.room['stop_pop_user'] = ""
        self.room['stop_pop_act'] = ""
        all_horse_card = []
        horse_card = []
        horse_num = 0
        horse = self.room['horse']
        if horse:
            horse = int(horse)
            all_horse_card, horse_card = self.get_horse(horse, uid)
            horse_num = len(horse_card)
        
        member_len = len(self.members)
        match_id = self.room['mid']
        if match_id:
            #win_score = 1
            all_round = int(self.room['all_round'])
            game_round = int(self.room['game_round'])
            win_score = get_match_base_score(self.bid, match_id, all_round, game_round, self.rid)
        else:
            base_score = 1
            win_score = base_score * (1 + horse_num)
        #win_score = 2 * horse_num * (member_len - 1) + (member_len - 1)
        
        logging.info(u"房间:%s用户%s点炮胡,中%s马,得%s分" % (self.rid, uid, horse_num, win_score))
        #grab_bar_duty = self.room['grab_bar_duty']
        p.score['score'] = int(p.score['score']) + win_score
            
        mid = self.incr_mid()
        for member in self.members:
            if member != uid:
                player = Player(member, self.bid)
                # 抢杠胡全包
                if member == last_put_user:
                    player.score['score'] = int(player.score['score']) - win_score
                    logging.info(u"房间:%s用户%s点炮胡,中%s马,点炮全包:%s, 扣%s分" % (self.rid, uid, horse_num, last_put_user, win_score))
            nsq_pub({"b":self.bid, "u":str(member), "t":"game", "d":{"mid":mid, "act":"win", "card":card, "tips":[], "rid":self.rid, "uid":uid, "all_horse_card":all_horse_card, "horse_card":horse_card, "horse_num":horse_num}})
        self.game_over(uid, card, all_horse_card, horse_card, horse_num, win_type="put_win")
        
if __name__ == "__main__":
    tdh = MaJiang('100016', 'szjt')
    tdh.pass_card('', '')
    
